package com.logica.hackthon.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import com.flca.frw.context.FlcaContext;
import com.flca.frw.context.FlcaCtx;
import com.logica.hackthon.HackThonContext;
import com.logica.hackthon.entity.Player;
import com.logica.hackthon.service.IHackThonService;

@Path("HackThonService")
public class RegisterRestSrv 
{
	private static Logger logger = Logger.getLogger(RegisterRestSrv.class);

	private static ObjectMapper om = new ObjectMapper();

//	@Context
//	private UriInfo uriInfo;
//	
//	@Context
//	private Request request;
	
	private static IHackThonService sService;
	

	protected static IHackThonService getService()
	{
		if (sService == null) {
			sService = HackThonContext.INSTANCE.getInjector().getInstance(IHackThonService.class);
		}
		
		return sService;
	}
	
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("register")
	
	public String register(@QueryParam("player") String aPlayer, @QueryParam("flcaContext") String aJsonFlcaContext) 
	{
		try {
			FlcaContext ctx = makeFlcaCtx(aJsonFlcaContext);
			Player p = om.readValue(aPlayer, Player.class);
			Player result = getService().register(p, ctx);
			return om.writeValueAsString(result);
		} catch (Exception e) {
			logger.error("error in RegisterRestSrv.register ", e);
			throw new RuntimeException(e);
		}
	}

	private FlcaCtx makeFlcaCtx(String aJsonContext) 
	{
		try {
			FlcaContext flcaContext = FlcaContext.fromJsonString(aJsonContext);
			return new FlcaCtx(flcaContext);
		} catch (Exception e) {
			logger.error("error deserializing json FlcaContext ", e);
			throw new RuntimeException(e);
		}
	}
}
